package com.ant.storage.service.impl;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.ant.storage.common.ResultCode;
import com.ant.storage.common.ResultVo;
import com.ant.storage.dto.CashbookDto;
import com.ant.storage.handler.AntException;
import com.ant.storage.mapper.CashbookBalanceMapper;
import com.ant.storage.mapper.CashbookMapper;
import com.ant.storage.pojo.*;
import com.ant.storage.service.ICashbookService;
import com.ant.storage.service.IInvoiceInfoService;
import com.ant.storage.service.IPurchaserRecordImgService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author melon
 * @since 2023-11-09
 */
@Service
public class CashbookServiceImpl extends ServiceImpl<CashbookMapper, Cashbook> implements ICashbookService {

    @Value("${loginUrl.url}")
    private String Url;

    @Autowired
    public ServletContext servletContext;

    @Resource
    private CashbookBalanceMapper balanceMapper;

    @Resource
    private IInvoiceInfoService infoService;

    @Resource
    private IPurchaserRecordImgService imgService;

    @Override
    public   PageInfo<Cashbook> queryList(CashbookDto dto) {
        try {
            PageHelper.startPage(dto.getPageIndex(), dto.getPageSize());
            QueryWrapper<Cashbook> wrapper = new QueryWrapper<>();
            if(dto.getCityId()!=null){
                wrapper.eq("city_id",dto.getCityId());
            }
            if(dto.getHandledby()!=null &&!("").equals(dto.getHandledby())){
                wrapper.eq("handled_by",dto.getHandledby());
            }
            if(dto.getTimes()!=null && dto.getTimes().length!=0){
                wrapper.ge("create_time",dto.getTimes()[0]+" 00:00:00");
                wrapper.le("create_time",dto.getTimes()[1] +" 23:59:59");
            }
            if(dto.getSubjectType()!=null && dto.getSubjectType().length!=0){
                wrapper.in("subject_type",Arrays.asList(dto.getSubjectType()));
            }

            if(dto.getCashbookType()!=null){
                wrapper.eq("cashbook_type",dto.getCashbookType());
            }

            wrapper.orderByDesc("id");
            PageInfo<Cashbook> info = new PageInfo<>(this.baseMapper.selectList(wrapper));
            return info;
        } catch (Exception e) {
            throw new AntException(ResultCode.BODY_NOT_MATCH.getResultCode(),e.getMessage());
        }
    }

    @Override
    public ResultVo saveCashbook(Cashbook cashbook) {
        UserInfo userInfo = (UserInfo) servletContext.getAttribute("userInfo");
        cashbook.setCityId(cashbook.getCityId());
        cashbook.setDates(new Date());
        cashbook.setAnnexId(cashbook.getImgId());
        cashbook.setCreateTime(new Date());
        cashbook.setCreatorBy(userInfo.getUserName());
        cashbook.setHandledBy(userInfo.getUserName());
        Cashbook maxList = this.baseMapper.selectMaxList(cashbook.getCityId());
        BigDecimal balancePrice=new BigDecimal("0");
        if(maxList!=null){
            balancePrice=maxList.getBalance();
        }
        BigDecimal newBalance=balancePrice.add(cashbook.getIncome()).subtract(cashbook.getExpend());
        cashbook.setBalance(newBalance);
        this.baseMapper.insert(cashbook);
        CashbookBalance balance=new CashbookBalance();
        balance.setCashbookId(cashbook.getId());
        balance.setBalanceId(cashbook.getBalanceId());
        balance.setBalanceType(cashbook.getBalanceType().toString());
        balanceMapper.insert(balance);
        if(cashbook.getBalanceType()==3){
            infoService.update(new UpdateWrapper<InvoiceInfo>().set("is_balance",1).eq("id",cashbook.getSourcesId()));
        }
        return ResultVo.success("操作成功");
    }


    /**
     * 批量保存流水
     * @param list
     * @return
     */
    @Override
    public ResultVo saveBatchs(List<Cashbook> list) {
        UserInfo userInfo = (UserInfo) servletContext.getAttribute("userInfo");
        list.stream().forEach(item -> {
            Cashbook maxList = this.baseMapper.selectMaxList(item.getCityId());
            BigDecimal newBalance=maxList.getBalance().add(item.getIncome()).subtract(item.getExpend());
            // 余额是否小于0
            if(newBalance.compareTo(BigDecimal.ZERO)<0){
                throw new AntException(ResultCode.FAILURE.getCode(), "账号余额不足");
            }
            item.setBalance(newBalance);
            item.setAnnexId(item.getImgId());
            item.setDates(new Date());
            item.setCreateTime(new Date());
            item.setCreatorBy(userInfo.getUserName());
            this.baseMapper.insert(item);
      });
        CashbookBalance balance=new CashbookBalance();
        balance.setCashbookId(list.get(0).getId());
        balance.setBalanceId(list.get(0).getBalanceId());
        balance.setBalanceType(list.get(0).getBalanceType().toString());
        balanceMapper.insert(balance);
        return ResultVo.success("操作成功");
    }

    /**
     * 手动结算单后，自动生成流水
     * @return
     */
    @Override
    public ResultVo balance() {
        UserInfo userInfo = (UserInfo) servletContext.getAttribute("userInfo");
        String countExpend = this.baseMapper.getCountExpend(userInfo.getCityId());
        if(countExpend==null){
            throw new AntException(ResultCode.FAILURE.getCode(), "请先添加流水记录");
        }
        String countBalance = this.baseMapper.getCountBalance(userInfo.getCityId());
        BigDecimal balance = new BigDecimal("0");
        if(countBalance != null){
            balance=new BigDecimal(countBalance);
        }
        String countIncome = this.baseMapper.getCountIncome(userInfo.getCityId());
        BigDecimal Income= new BigDecimal("0");
        if(countIncome != null){
            Income=new BigDecimal(countIncome);
        }
        BigDecimal Expend= new BigDecimal(countExpend);

        balance=balance.add(Income).subtract(Expend);

        Cashbook  cashbook =new Cashbook();
        cashbook.setIncome(Income);
        cashbook.setExpend(Expend);
        cashbook.setBalance(balance.setScale(5,BigDecimal.ROUND_HALF_UP));
        cashbook.setDates(new Date());
        cashbook.setCreateTime(new Date());
        cashbook.setAbstracts("本日合计");
        cashbook.setSources("系统生成");
        cashbook.setCarryForward(1);
        cashbook.setCreatorBy(userInfo.getUserName());
        cashbook.setCityId(userInfo.getCityId());
        this.baseMapper.insert(cashbook);
        return ResultVo.success("获取成功");
    }


    /**
     * 自动结算单后，自动生成流水
     * @return
     */
    @Override
    public ResultVo automaticBalance() {
        QueryWrapper<Cashbook> wrapper = new QueryWrapper<>();
        wrapper.groupBy("city_id").select("city_id");
        List<Map<String, Object>> mapList = this.baseMapper.selectMaps(wrapper);
        mapList.stream().forEach(item -> {
            Integer cityId = (Integer) item.get("city_id");
            String countExpend = this.baseMapper.getCountExpend(cityId);
            if(countExpend==null){
                throw new AntException(ResultCode.FAILURE.getCode(), "请先添加流水记录");
            }
            String countBalance = this.baseMapper.getCountBalance(cityId);
            BigDecimal balance = new BigDecimal("0");
            if(countBalance != null){
                balance=new BigDecimal(countBalance);
            }
            String countIncome = this.baseMapper.getCountIncome(cityId);
            BigDecimal Income= new BigDecimal("0");
            if(countIncome != null){
                Income=new BigDecimal(countIncome);
            }
            BigDecimal Expend= new BigDecimal(countExpend);
            balance=balance.add(Income).subtract(Expend);
            Cashbook  cashbook =new Cashbook();
            cashbook.setIncome(Income);
            cashbook.setExpend(Expend);
            cashbook.setBalance(balance.setScale(5,BigDecimal.ROUND_HALF_UP));
            cashbook.setDates(new Date());
            cashbook.setCreateTime(new Date());
            cashbook.setAbstracts("本日合计");
            cashbook.setSources("系统生成");
            cashbook.setCarryForward(1);
            cashbook.setCityId(cityId);
            this.baseMapper.insert(cashbook);
        });
        return ResultVo.success("获取成功");
    }

    @Override
    public String getBalance(String id, HttpServletRequest request) {
        UserInfo userInfo = (UserInfo) servletContext.getAttribute("userInfo");
        Cashbook  cashbook =new Cashbook();
        cashbook.setDates(new Date());
        cashbook.setCreateTime(new Date());
        String token = request.getHeader("token");
        String urlStr = Url +"/car/carReimbursement/queryContent?id="+id;
        Map<String, Object> paramMap=new HashMap<>();
        paramMap.put("Token",token);
        String str = HttpUtil.createGet(urlStr).header("Token",token).execute().body();
        JSONObject object = JSONUtil.parseObj(str);
        Integer code = (Integer) object.get("code");
        if(code==200){
            String data = object.get("data").toString();
            JSONObject objectData = JSONUtil.parseObj(data);
            //这里需要获取到金额
            cashbook.setIncome(new BigDecimal(objectData.get("money").toString()));
            //这里需要获取到金额
            cashbook.setExpend(new BigDecimal("0"));
            Cashbook maxList = this.baseMapper.selectMaxList(userInfo.getCityId());
            BigDecimal newBalance=maxList.getBalance().add(cashbook.getIncome()).subtract(cashbook.getExpend());
            cashbook.setBalance(newBalance);
            cashbook.setCityId((Integer) objectData.get("cityId"));
            cashbook.setCashbookType((Integer) objectData.get("type"));
            cashbook.setCreatorBy(objectData.get("userName").toString());
            cashbook.setAbstracts(filterStatus((Integer) objectData.get("type")));
            cashbook.setNotes(objectData.get("remarks").toString());
            cashbook.setSources("系统生成");
            this.baseMapper.insert(cashbook);
        }
        return str;
    }

    @Override
    public Cashbook getBalanceId(Integer id) {
        if(id==null){
            throw new AntException(ResultCode.BODY_NOT_MATCH.getCode(),"id不能为空");
        }
        Cashbook cashbook = this.baseMapper.selectOne(new QueryWrapper<Cashbook>().eq("id", id));
        if(cashbook.getAnnexId()!=null){
            List<PurchaserRecordImg> list = imgService.list(new QueryWrapper<PurchaserRecordImg>().in("id",
                    Arrays.asList(cashbook.getAnnexId().split(","))));
            cashbook.setImglist(list);
        }
        return cashbook;
    }

    @Override
    public List<Cashbook> getBalanceIds(String ids) {
        List<Cashbook> list = this.baseMapper.selectList(new QueryWrapper<Cashbook>().in("id", Arrays.asList(ids.split(
                ","))));
//        list.stream().forEach(item -> {
//
//            if(item.getIncome().compareTo(BigDecimal.ZERO)==0){
//                if(item.getExpend().compareTo(BigDecimal.ZERO)==0){
//                    item.setAccountingPrice(new BigDecimal("0"));
//                }else{
//                    item.setAccountingPrice(item.getExpend());
//                }
//            }else{
//                item.setAccountingPrice(item.getIncome());
//            }
//
//        });
        return list;
    }

    //过滤状态对应的值
    public String filterStatus(Integer status){
        String str="报销";
        if(status==22){
            return "违法（个人）"+str;
        }
        if(status==2){
            return "违法（因公）"+str;
        }
        if(status==7){
            return "事故"+str;
        }
        if(status==21){
            return "事故流程"+str;
        }
        if(status==8){
           return  "维修"+str;
        }
        if(status==3){
            return "保养"+str;
        }
        if(status==11){
            return "车广"+str;
        }
        if(status==12){
            return "耗材"+str;
        }
        if(status==4){
            return "轮胎"+str;
        }
        if(status==5){
            return "电瓶"+str;
        }
        if(status==14){
            return "保险"+str;
        }
        if(status==10){
            return "年审"+str;
        }
        if(status==19){
            return "保险追加"+str;
        }
        if(status==19){
            return "年审"+str;
        }
        if(status==15){
            return "调拨"+str;
        }
        if(status==23){
            return "过户"+str;
        }
        if(status==17){
            return "报废"+str;
        }
        if(status==16){
            return "变卖"+str;
        }
        if(status==18){
            return "租赁"+str;
        }
        if(status==20){
            return "出租"+str;
        }
        if(status==6){
            return "gps"+str;
        }
        if(status==24){
            return "政府业务"+str;
        }
        if(status==25){
            return "尾板新增"+str;
        }
        if(status==26){
            return "尾板调拨"+str;
        }
        if(status==27){
            return "尾板过户"+str;
        }
        if(status==28){
            return "尾板报废"+str;
        }
        if(status==29){
            return "尾板维修"+str;
        }
        if(status==30){
            return "尾板保养"+str;
        }
        return "报销";
    }
}
